package appcus

import (
	"counter-help/admin/server/global"
	customerReq "counter-help/admin/server/model/app/request"
	customerRes "counter-help/admin/server/model/app/response"
	"counter-help/admin/server/model/audit"
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/model/customer"
	"counter-help/admin/server/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"strconv"
	"time"
)

type CusOrderAssignmentsApi struct{}

// CreateCusOrderAssignments 创建cusOrderAssignments表
// @Tags CusOrderAssignments
// @Summary 创建cusOrderAssignments表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customer.CusOrderAssignments true "创建cusOrderAssignments表"
// @Success 200 {object} response.Response{msg=string} "创建成功"
// @Router /cusOrderAssignments/createCusOrderAssignments [post]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) CreateCusOrderAssignments(c *gin.Context) {
	var cusOrderAssignments customerReq.CreateCusOrderAssignmentsSearch
	err := c.ShouldBindJSON(&cusOrderAssignments)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	userId := int(utils.GetUserID(c))

	// 检查用户认证信息
	missingCertifications := checkUserCertifications(userId, "OrderAssignments")

	if len(missingCertifications) > 0 {
		var detailedMessage string
		for _, certMessage := range missingCertifications {
			// 生成更详细的消息
			detailedMessage += certMessage + "；"
		}

		// 移除最后一个分号
		if len(detailedMessage) > 0 {
			detailedMessage = detailedMessage[:len(detailedMessage)-1]
		}

		// 提供详细的提示信息
		response.CommonFailWithMessage("请先完成以下认证："+detailedMessage, c)
		return
	}

	// 查询订单信息，检查用户是否是订单创建者
	var order customer.CusOrder
	err = global.GVA_DB.Where("id = ?", cusOrderAssignments.OrderId).First(&order).Error
	if err != nil {
		response.FailWithMessage("订单不存在或查询失败", c)
		return
	}

	// 判断当前用户是否为订单创建者
	if order.OrderUserId == userId {
		response.FailWithMessage("无法接自己的订单", c)
		return
	}

	// 检查是否已有接单记录
	var existingAssignment customer.CusOrderAssignments
	err = global.GVA_DB.Where("user_id = ? AND order_id = ?", userId, cusOrderAssignments.OrderId).First(&existingAssignment).Error
	if err == nil {
		// 存在接单记录，更新时间字段
		err = global.GVA_DB.Model(&existingAssignment).Update("updated_at", time.Now()).Error
		if err != nil {
			global.GVA_LOG.Error("更新失败!", zap.Error(err))
			response.FailWithMessage("更新失败:"+err.Error(), c)
			return
		}
		response.OkWithMessage("接单记录已更新", c)
		return
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		// 其他查询错误
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}

	// 若不存在接单记录，则创建新的接单记录
	isFinal := false
	orderAssignments := &customer.CusOrderAssignments{
		UserId:  &userId,
		OrderId: cusOrderAssignments.OrderId,
		IsFinal: &isFinal,
	}
	err = cusOrderAssignmentsService.CreateCusOrderAssignments(orderAssignments)
	if err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败:"+err.Error(), c)
		return
	}

	response.OkWithMessage("创建成功", c)
}

// 检查用户的认证信息
func checkUserCertifications(userId int, createType string) []string {
	var missingCertifications []string
	isCertifications := false
	// 判断创建类型，针对不同类型做不同的检查
	//if createType == "OrderAssignments" {
	// 检查 TechnicalVerification 表
	var technicalVerification audit.TechnicalVerification
	if err := global.GVA_DB.Where("user_id = ?", userId).First(&technicalVerification).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		//missingCertifications = append(missingCertifications, "技术认证")
	} else {

		// 认证存在，检查状态
		if !technicalVerification.IsReviewed {
			//missingCertifications = append(missingCertifications, "技术认证尚未审核")
		} else if !technicalVerification.IsApproved {
			//reason := "驳回原因: " + technicalVerification.RejectionReason
			//missingCertifications = append(missingCertifications, "技术认证未通过。"+reason)
		} else {
			isCertifications = true
		}
	}
	//}

	// 检查 UserIdentity 表
	var userIdentity audit.UserIdentity
	if err := global.GVA_DB.Where("user_id = ?", userId).First(&userIdentity).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		//missingCertifications = append(missingCertifications, "身份认证")
	} else {
		// 认证存在，检查状态
		if !userIdentity.IsReviewed {
			//	missingCertifications = append(missingCertifications, "身份认证尚未审核")
		} else if !userIdentity.IsApproved {
			//reason := "驳回原因: " + userIdentity.RejectionReason
			//missingCertifications = append(missingCertifications, "身份认证未通过。"+reason)
		} else {
			isCertifications = true
			fmt.Println("认证完成33333333333", userId)
		}
	}

	// 检查 EducationVerification 表
	var educationVerification audit.EducationVerification
	if err := global.GVA_DB.Where("user_id = ?", userId).First(&educationVerification).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		//	missingCertifications = append(missingCertifications, "学历认证")
	} else {
		// 认证存在，检查状态
		if !educationVerification.IsReviewed {
			//	missingCertifications = append(missingCertifications, "学历认证尚未审核")
		} else if !educationVerification.IsApproved {
			//reason := "驳回原因: " + educationVerification.RejectionReason
			//missingCertifications = append(missingCertifications, "学历认证未通过。"+reason)
		} else {
			isCertifications = true
		}

	}
	if isCertifications == false {
		missingCertifications = append(missingCertifications, "身份认证或者技术认证或者学历认证")
	}

	fmt.Print("认证结果", missingCertifications)

	return missingCertifications
}

// DeleteCusOrderAssignments 删除cusOrderAssignments表
// @Tags CusOrderAssignments
// @Summary 删除cusOrderAssignments表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customer.CusOrderAssignments true "删除cusOrderAssignments表"
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /cusOrderAssignments/deleteCusOrderAssignments [delete]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) DeleteCusOrderAssignments(c *gin.Context) {
	ID := c.Param("ID")
	// 将 ID 转换为 int 类型
	id, err := strconv.Atoi(ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败，ID 无效", zap.Error(err))
		response.FailWithMessage("删除失败，ID 无效", c)
		return
	}
	UserID := int(utils.GetUserID(c))
	err = cusOrderAssignmentsService.DeleteCusOrderAssignments(id, UserID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteCusOrderAssignmentsByIds 批量删除cusOrderAssignments表
// @Tags CusOrderAssignments
// @Summary 批量删除cusOrderAssignments表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "批量删除成功"
// @Router /cusOrderAssignments/deleteCusOrderAssignmentsByIds [delete]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) DeleteCusOrderAssignmentsByIds(c *gin.Context) {
	IDs := c.QueryArray("IDs[]")
	err := cusOrderAssignmentsService.DeleteCusOrderAssignmentsByIds(IDs)
	if err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("批量删除成功", c)
}

// UpdateCusOrderAssignments 更新cusOrderAssignments表
// @Tags CusOrderAssignments
// @Summary 更新cusOrderAssignments表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customer.CusOrderAssignments true "更新cusOrderAssignments表"
// @Success 200 {object} response.Response{msg=string} "更新成功"
// @Router /cusOrderAssignments/updateCusOrderAssignments [put]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) UpdateCusOrderAssignments(c *gin.Context) {
	var cusOrderAssignments customer.CusOrderAssignments
	err := c.ShouldBindJSON(&cusOrderAssignments)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = cusOrderAssignmentsService.UpdateCusOrderAssignments(cusOrderAssignments)
	if err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

// FindCusOrderAssignments 用id查询cusOrderAssignments表
// @Tags CusOrderAssignments
// @Summary 用id查询cusOrderAssignments表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query customer.CusOrderAssignments true "用id查询cusOrderAssignments表"
// @Success 200 {object} response.Response{data=customer.CusOrderAssignments,msg=string} "查询成功"
// @Router /cusOrderAssignments/findCusOrderAssignments [get]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) FindCusOrderAssignments(c *gin.Context) {
	ID := c.Query("ID")
	recusOrderAssignments, err := cusOrderAssignmentsService.GetCusOrderAssignments(ID)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithData(recusOrderAssignments, c)
}

// GetCusOrderAssignmentsList 分页获取cusOrderAssignments表列表
// @Tags CusOrderAssignments
// @Summary 分页获取cusOrderAssignments表列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query customerReq.CusOrderAssignmentsSearch true "分页获取cusOrderAssignments表列表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
// @Router /cusOrderAssignments/getCusOrderAssignmentsList [get]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) GetCusOrderAssignmentsList(c *gin.Context) {
	var pageInfo customerReq.CusOrderAssignmentsSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := cusOrderAssignmentsService.GetCusOrderAssignmentsInfoList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetCusOrderAssignmentsPublic 不需要鉴权的cusOrderAssignments表接口
// @Tags CusOrderAssignments
// @Summary 不需要鉴权的cusOrderAssignments表接口
// @accept application/json
// @Produce application/json
// @Param data query customerReq.CusOrderAssignmentsSearch true "分页获取cusOrderAssignments表列表"
// @Success 200 {object} response.Response{data=object,msg=string} "获取成功"
// @Router /cusOrderAssignments/getCusOrderAssignmentsPublic [get]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) GetCusOrderAssignmentsPublic(c *gin.Context) {
	// 此接口不需要鉴权
	// 示例为返回了一个固定的消息接口，一般本接口用于C端服务，需要自己实现业务逻辑
	response.OkWithDetailed(gin.H{
		"info": "不需要鉴权的cusOrderAssignments表接口信息",
	}, "获取成功", c)
}

// GetCusOrdersByUserID 通过userID获取cusOrderAssignments表，并关联获取cusOrder表信息
// @Tags CusOrderAssignments
// @Summary 通过userID获取cusOrderAssignments表，并关联获取cusOrder表信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param userID query int true "用户ID"
// @Success 200 {object} response.Response{data=[]customer.CusOrder,msg=string} "获取成功"
// @Router /cusOrderAssignments/getCusOrdersByUserID [get]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) GetCusOrdersByUserID(c *gin.Context) {
	// 获取查询参数 userID
	userID := int(utils.GetUserID(c))

	// 查询 CusOrderAssignments 表
	cusOrderAssignments, err := cusOrderAssignmentsService.GetCusOrderAssignmentsByUserID(userID)
	if err != nil {
		global.GVA_LOG.Error("获取CusOrderAssignments失败!", zap.Error(err))
		response.FailWithMessage("获取CusOrderAssignments失败:"+err.Error(), c)
		return
	}

	// 根据 CusOrderAssignments 中的 order_id 查询 CusOrder 表
	var orders []customerRes.CusOrderListResponse
	for _, assignment := range cusOrderAssignments {
		if assignment.OrderId == nil {
			continue // 跳过没有关联订单的记录
		}
		orderID := strconv.Itoa(*assignment.OrderId) // 将 *int 转换为 string
		order, err := cusOrderService.GetCusOrderByID(orderID)
		if err != nil {
			global.GVA_LOG.Error("获取CusOrder失败!", zap.Error(err))
			response.FailWithMessage("获取CusOrder失败:"+err.Error(), c)
			return
		}
		orders = append(orders, order)
	}

	// 返回结果
	response.OkWithData(orders, c)
}

// GetUsersByOrderID 根据order_id获取相关用户信息
// @Tags CusOrderAssignments
// @Summary 根据order_id获取相关用户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param order_id query int true "订单ID"
// @Success 200 {object} response.Response{data=[]customer.User,msg=string} "获取成功"
// @Router /cusOrderAssignments/getUsersByOrderID [get]
func (cusOrderAssignmentsApi *CusOrderAssignmentsApi) GetUsersByOrderID(c *gin.Context) {
	// 获取查询参数 order_id
	orderIDParam := c.Query("order_id")
	orderID, err := strconv.Atoi(orderIDParam)
	if err != nil {
		response.FailWithMessage("无效的order_id参数", c)
		return
	}

	// 根据order_id查询CusOrderAssignments表中的所有user_id
	userIDs, err := cusOrderAssignmentsService.GetUserIDsByOrderID(orderID)
	if err != nil {
		global.GVA_LOG.Error("获取CusOrderAssignments中的user_id失败!", zap.Error(err))
		response.FailWithMessage("获取CusOrderAssignments中的user_id失败:"+err.Error(), c)
		return
	}

	// 根据user_id列表查询cus_user表中的用户信息
	users, err := appUserService.GetUsersByIDList(userIDs)
	if err != nil {
		global.GVA_LOG.Error("获取用户信息失败!", zap.Error(err))
		response.FailWithMessage("获取用户信息失败:"+err.Error(), c)
		return
	}

	// 返回用户信息
	response.OkWithData(users, c)
}
